﻿using MaterialTypeRecognition.Shell.Uers;
using MaterialTypeRecognition.Shell.UnitOfWork;
using System;
using System.Security.Claims;
using System.Threading.Tasks;

namespace MaterialTypeRecognition.Shell.AuthenticationServices
{
    /// <summary>
    /// 用户认证服务。
    /// </summary>
    public class UserAuthenticationService : IUserAuthenticationService
    {
        public UserAuthenticationService(IJwtBearerService jwtBearer, IUserRepository userRepository)
        {
            _jwtBearer = jwtBearer;
            _repository = userRepository;
        }

        /// <summary>
        /// 用户仓储。
        /// </summary>
        private readonly IRepository<User> _repository;

        /// <summary>
        /// JWT Bearer。
        /// </summary>
        private readonly IJwtBearerService _jwtBearer;

        /// <summary>
        /// 注销用户认证信息。
        /// </summary>
        /// <param name="userName"></param>
        public Task CancelAuthenticationAsync(string userName)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 进行身份认证。
        /// </summary>
        /// <param name="userModel">用户模型。</param>
        public async Task<AuthenticationResultDto> TryAuthenticateAsync(UserModelDto userModel)
        {
            var loginUser = await _repository.GetFirstOrDefaultAsync(user => user.Key == userModel.Key, null, null, true, false);

            if (loginUser == null || loginUser.Key != userModel.Key)
            {
                return new AuthenticationResultDto();
            }

            return new AuthenticationResultDto(_jwtBearer.GetJwtToken(builder =>
            {
                builder.AddClaim(new Claim("Permission", loginUser.Permission));
            }));
        }
    }
}
